import { defineStore } from 'pinia';
import { store } from '../index';
import { getAccessToken, getTenantId } from '@/utils/auth';
const { wsCache } = useCache();
import * as ApiMsg from '@/api/msg';
import * as ApiCommon from '@/api/common';
interface LocaleState {
    imStore: {
        userList: string[]
        chatList: string[]
    }
    websocket: any
    websocketMsg: any
    isConnected: boolean
    pingInterval: any
    pongTimeout: any
    pingTime: number
    pongTime: number
}
export const websocketStore = defineStore('websocket', {
	state: (): LocaleState => {
		return {
            imStore: {
                userList: [], // 用户列表
                chatList: [], // 左侧会话列表
            },
			websocket: null,
            websocketMsg: null,
            isConnected: false,
            pingInterval: null,
            pongTimeout: null,
            pingTime: 30000, // 30秒发送一次ping
            pongTime: 65000, // 65秒(第二次连接再5秒后)未收到pong则认为连接失效
		};
	},
	getters: {},
	actions: {
        // 用户列表
        async getUserList () {
            try{
                const res = await ApiCommon.ApiUserList();
                this.imStore.userList = res || [];
                wsCache.set('imStore', this.imStore);
            }catch(err){console.log(err);}
        },
        // 消息列表 
        async getChatList () {
            try{
                let res = await ApiMsg.ApiChatList();
                if(res && res.length > 0){
                    this.imStore.chatList = res?.map(item => {
                        item.topicId = item.id;
                        item.lastMsg.content = item.lastMsg?.content?.replace(/<p>/g, '')?.replace(/<\/p>/g, ' ')?.replace(/\s+/g,' ');
                        item.sendName = this.imStore.userList?.find(child => child.id === item.lastMsg?.sendId)?.nickname;
                        item.chatType = 'chat';
                        if(item.messageType === 'SYSTEM_MESSAGE'){
                            item.chatType = 'app';
                            item.isEmpty = false;
                        }
                        if(item.lastMsg?.content?.includes('<img')){
                            item.lastMsg.content = item.lastMsg.content.replace(/<img.*?>/g, "[图片]");
                        }
                        item.lastMsg.content = item.lastMsg?.content?.replace(/<[^>]*>/g,' ');
                        return item;
                    }) || [];
                    wsCache.set('imStore', this.imStore);
                    window.dispatchEvent(new Event('storage')); // 修改 storage 时手动触发
                }
            }catch(err){console.log(err);}
        },
        // 绑定登录人
        async handleBindUser() {
            try{
                await ApiMsg.ApiChatBind();
            }catch(err){console.log(err);}
		},
        // 关闭websocket
        closeWebsocket(){
            console.log('关闭====');
            if (this.websocket){
                this.websocket.close();
                this.websocket = ''
                clearInterval(this.pingInterval);
                clearTimeout(this.pongTimeout);
            };
        },
        // 发送ping请求
        sendPing() {
            if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
                this.websocket.send('ping');
                // console.log('发送ping请求');
            }
        },
        // 设置imStore
        setChatList(data){
            this.imStore.chatList = data;
            wsCache.set('imStore', this.imStore);
            window.dispatchEvent(new Event('storage')); // 修改 storage 时手动触发
        },
        // 重设pong超时计时器
        setPong(){
            clearTimeout(this.pongTimeout);
            this.pongTimeout = setTimeout(this.handleNoPong, this.pongTime);
        },
        // 收到pong回复
        handleNoPong () {
            // console.log('超过30秒未收到pong，正在重新连接...');
            this.websocket.onopen();
            this.connectWebSocket(); // 尝试重新连接
        },
        setWebsocket(data){
            this.websocket = data;
        },
		connectWebSocket() {
            // setTimeout(() => {
                const ws = new WebSocket(`${import.meta.env.VITE_IM_URL}?token=${getAccessToken()}&tenantId=${getTenantId()}`);
                // console.log('拿到====', this.websocket);
                // const ws = this.websocket;
                wsCache.set('websocket', ws);
                ws.onopen = () => {
                    console.log('WebSocket已连接===im');
                    this.isConnected = true;
                    this.handleBindUser(); // 登录人
                    this.pingInterval = setInterval(this.sendPing, this.pingTime); // 每30秒发送一次ping
                    this.pongTimeout = setTimeout(this.handleNoPong, this.pongTime); // 初始检测
                };
                ws.onmessage = (event) => {
                    console.log('event====', event);
                    if(event?.data === 'pong'){
                        this.setPong();
                        return;
                    };
                    const { chatList, userList } = wsCache.get('imStore');
                    let chat:any = JSON.parse(JSON.stringify(chatList));
                    let { sendId, topicId, content, sendTime } = JSON.parse(event.data).content;
                    console.log('收到消息====store', JSON.parse(event.data).content);
                    let items = chatList.find(item => item.topicId === topicId);
                    const itemsIndex = chatList.findIndex(item => item.topicId === topicId);
                    const isMyself = wsCache.get('userInfo')?.userId === sendId;
                    if(items){
                        items = {
                            ...items,
                            sendTime,
                            sendName: userList.find(child => child.id === sendId)?.nickname,
                            unread: isMyself ? 0 : (items?.unread || 0) + 1,
                        }
                        items.lastMsg.content = content.replace(/<img.*?>/g, "[图片]").replace(/<[^>]*>/g,' ');
                        chat.splice(itemsIndex, 1);
                        chat.unshift(items);
                        wsCache.set('imStore', {
                            chatList: chat,
                            userList
                        });
                    }
                    wsCache.set('websocketMsg', {...JSON.parse(event.data).content, sendType: JSON.parse(event.data).type});
                    window.dispatchEvent(new Event('storage')); // 修改 storage 时手动触发
                    wsCache.delete('websocketMsg');
                };
                ws.onclose = (event) => {
                    this.isConnected = false;
                    console.log('WebSocket已关闭', event);
                    clearInterval(this.pingInterval); // 清除ping定时器
                    clearTimeout(this.pongTimeout); // 清除pong定时器
                };
                ws.onerror = (error) => {
                    console.log('WebSocket出错', error);
                    clearInterval(this.pingInterval); // 清除ping定时器
                    clearTimeout(this.pongTimeout); // 清除pong定时器
                };
            // }, 1000);
        },
	}
});

export const websocketStoreWithOut = () => {
	return websocketStore(store);
};
